/**
 * User: alesj
 * Date: 2005.3.24
 * Time: 10:51:52
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.generalynx.ecos.utils;

import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class LoggerOutputStream extends OutputStream {

    private Log logger;
    private int priority;
    private final StringBuffer output = new StringBuffer();
    private boolean closed;

    public LoggerOutputStream() {
        this(LogFactory.getLog(LoggerOutputStream.class));
    }

    public LoggerOutputStream(Log logger) {
        this(logger, 1);
    }

    public LoggerOutputStream(Log logger, int priority) {
        this.logger = logger;
        this.priority = priority;
    }

    public void close() throws IOException {
        flush();
        super.close();
        closed = true;
    }

    public void write(int data) throws IOException {
        checkValid();
        output.append((char)data);
        if (10 == data) {
            flush();
        }
    }

    public synchronized void flush() throws IOException {
        checkValid();
        if (output.length() > 0) {
            log();
        }
        output.setLength(0);
    }

    private void checkValid() throws IOException {
        if (closed) {
            throw new EOFException("LoggerOutputStream closed");
        }
    }

    private void log() {
        switch(priority) {
            case 1 :
                logger.debug(output);
                break;
            case 2 :
                logger.info(output);
                break;
            case 3 :
                logger.warn(output);
                break;
            case 4 :
                logger.error(output);
                break;
            case 5 :
                logger.fatal(output);
                break;
        }
    }

}
